<?php
/**
 * 用户管理模块
 */
namespace app\controllers\marketing;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\data\Pagination;
use app\models\EmailSystemEmail;
use app\models\marketing\User;
use app\components\EmailMarket;
use app\models\marketing\UserGroup;
use app\models\marketing\MailGroup;
use app\components\UserManageMarket;

class UserManageController extends \app\base\Controller
{
    
    /**
     * 用户列表
     */
    public function actionIndex()
    {
        $data = [];
        $siteInfo = [];
        
         
        $defaultPageSize = 20;
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
         // 查询网站相关的数据
        $formData = Yii::$app->request->$mothod();
        // 当前用户所有有权限的站点
        $siteInfo_tmp = Yii::$app->authority->getMarketEmailAccessSite();
        
        if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
            foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
                $siteInfo[$siteInfo_tmp_v['site_id']] = $siteInfo_tmp_v['name'];
            }
        }
        if (empty($siteInfo)) {
            exit('你好，你没有任何网站的相关权限');
        }
        
        // 当前用户所有有权限的站点结束
        $formData['siteInfo'] = $siteInfo;
       
        // 用户邮箱
        $formData['email'] = isset($formData['email']) ? $formData['email'] : '';
       
        // 时间相关
        $formData['time_type'] = isset($formData['time_type']) ? $formData['time_type'] : 1;
        $timeYearMonth = \yii::$app->bjTime->date('Y-m',time());
        $timeYearMonthStart = $timeYearMonth.'-01';
        $timeYearMonthCurrent = \yii::$app->bjTime->date('Y-m-d',time());
        if (isset($formData['reservation_time'])) {
            if (!empty($formData['reservation_time']) && preg_match('/[0-9]{4}-[0-9]{1,2}-[0-9]{1,2} - [0-9]{4}-[0-9]{1,2}-[0-9]{1,2}/i',$formData['reservation_time'])) {
                $reservationTimeArr = explode(' - ',$formData['reservation_time']);
                $formData['startTime'] = $reservationTimeArr[0];
                $formData['endTime'] = $reservationTimeArr[1];
            } else {
                $formData['startTime'] = '1970-01-01';
                $formData['endTime'] = $timeYearMonthCurrent;
            }
        } else {
             $formData['startTime'] = $timeYearMonthStart;
             $formData['endTime'] = $timeYearMonthCurrent;
        }
       
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://'; 
        $formUrl = explode('?',$http_type.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"])[0]; 
        // 当前搜索哪个网站的用户信息
        $formData['site_id'] = isset($formData['site_id']) ? $formData['site_id'] : array_keys($siteInfo)[0];
        
        // 搜索用户标签
        $formData['label'] = isset($formData['label']) ? $formData['label'] : 1;
        
        // 根据什么条件搜索邮箱
        $formData['email_search_condition'] = isset($formData['email_search_condition']) ? $formData['email_search_condition']:1;
        if ($formData['site_id']) {
            $flag = Yii::$app->authority->judgeMarketEmailHaveSite($formData['site_id']);
            if (!$flag) {
                 $this->sysMsg('警告', '你的账号没有权限!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
            }
        } 
        
        // 分页参数相关
        $page = Yii::$app->request->$mothod('page') ? Yii::$app->request->$mothod('page') : 1;
        $pageSize = Yii::$app->request->$mothod('pagesize') ? Yii::$app->request->$mothod('pagesize') : $defaultPageSize;
       
        $formData['page'] = $page;
        $formData['pageSize'] = $pageSize;
        
        
        // 保存用户结果数据
        $data_select = Yii::$app->usermanagemarket->getMarketUserList($formData);
        $totalCount = $data_select['totalCount'];
         // 分页相关
        $pages = new Pagination(['totalCount' =>$totalCount, 'pageSize' => $pageSize, 'defaultPageSize' => $pageSize]);
        
        return $this->render('//marketing//user-manage/list',[
            'data' => $data_select['user_info'],  
            'formData' => $formData,
            'site' => $site,
            'formUrl' => $formUrl,
            'pages' => $pages,
        ]);
    }
    
    /**
     *  退订
     */
    public function actionUnsub()
    {
        $mothod = strtolower(Yii::$app->request->getMethod());
        
        // 当前的系统，代表是营销邮件还是系统邮件
        $site = Yii::$app->request->$mothod('site');
        
        $formData = Yii::$app->request->$mothod();
        // 用户退订
        $returnData = Yii::$app->usermanagemarket->unsub($formData);
        echo json_encode($returnData);
        exit;
    }
    
    /**
     * 订阅
     */
    public function actionSub()
    {
        $mothod = strtolower(Yii::$app->request->getMethod());
        
        // 当前的系统，代表是营销邮件还是系统邮件
        $site = Yii::$app->request->$mothod('site');
        
        $formData = Yii::$app->request->$mothod();
        // 用户退订
        $returnData = Yii::$app->usermanagemarket->sub($formData);
        echo json_encode($returnData);
        exit;
    }
    
    /**
     * 手动添加内测
     */
    public function actionAddTest()
    {
        $mothod = strtolower(Yii::$app->request->getMethod());
        
        // 当前的系统，代表是营销邮件还是系统邮件
        $site = Yii::$app->request->$mothod('site');
        $formData = Yii::$app->request->$mothod();
        
        $returnData = [];
        // 判断站点相关
        if (isset($formData['site_id']) && $formData['site_id']) {
            
            // 判断有没有相关权限
            $flag = Yii::$app->authority->judgeMarketEmailHaveSite($formData['site_id']);
            if (!$flag) {
                $returnData['status'] = 100;
                $returnData['errorInfo'] = "您没有相关站点的权限";
                echo json_encode($returnData);
                exit;
            }
            
            if (isset($formData['email']) && $formData['email']) {
                // 判断邮箱格式是否正确
                $emailMarket = new EmailMarket();
                $isEmail = $emailMarket->isEmail($formData['email']);
                if ($isEmail) {
                    // 用户添加内侧
                    if (!empty($formData['no_redis'])) {    // 发送模板内测页面添加内测邮箱不加入到redis排队
                        $returnData = Yii::$app->usermanagemarket->addTestNoRedis($formData);
                    } else {
                        $returnData = Yii::$app->usermanagemarket->addTest($formData);
                    }
                } else {
                    $returnData['status'] = 3;
                    $returnData['errorInfo'] = "邮箱地址格式不正确";
                    echo json_encode($returnData);
                    exit;
                }
               
            } else {
                $returnData['status'] = 2;
                $returnData['errorInfo'] = "邮箱地址不能为空";
                echo json_encode($returnData);
                exit;
            }
            
        } else {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "必须选择归属网站";
            echo json_encode($returnData);
            exit;
        }
        
        echo json_encode($returnData);
        exit;
    }
    
    /**
     * 内测
     */
    public function actionInsideTest()
    {
        $mothod = strtolower(Yii::$app->request->getMethod());
        
        // 当前的系统，代表是营销邮件还是系统邮件
        $site = Yii::$app->request->$mothod('site');
        
        $formData = Yii::$app->request->$mothod();
        // 用户内侧
        $returnData = Yii::$app->usermanagemarket->insideTest($formData);
        echo json_encode($returnData);
        exit;
    }
    
    /**
     * 取消内测
     */
    public function actionUnInsideTest()
    {
        $mothod = strtolower(Yii::$app->request->getMethod());
        
        // 当前的系统，代表是营销邮件还是系统邮件
        $site = Yii::$app->request->$mothod('site');
        
        $formData = Yii::$app->request->$mothod();
        // 用户退订
        $returnData = Yii::$app->usermanagemarket->unInsideTest($formData);
        echo json_encode($returnData);
        exit;
    }
    
    /**
     *  添加到黑名单
     */
     public function actionAddToBlack()
    {
        $mothod = strtolower(Yii::$app->request->getMethod());
        
        // 当前的系统，代表是营销邮件还是系统邮件
        $site = Yii::$app->request->$mothod('site');
        
        $formData = Yii::$app->request->$mothod();
        // 用户退订
        $returnData = Yii::$app->usermanagemarket->addToBlack($formData);
        echo json_encode($returnData);
        exit;
    }
    
    /**
     * 取消黑名单
     */
    public function actionCancelBlack()
    {
        $mothod = strtolower(Yii::$app->request->getMethod());
        
        // 当前的系统，代表是营销邮件还是系统邮件
        $site = Yii::$app->request->$mothod('site');
        
        $formData = Yii::$app->request->$mothod();
        // 用户退订
        $returnData = Yii::$app->usermanagemarket->cancelBlack($formData);
        echo json_encode($returnData);
        exit;
    }
    
    /*
     * 上传csv文件批量导入用户数据
     * 
     */
    public function actionImportUnsubscribe()
    {
        set_time_limit(0);
        $mothod = strtolower(Yii::$app->request->getMethod());
        $formData = Yii::$app->request->$mothod();
        
        // 判断权限
        $flag = Yii::$app->authority->judgeMarketEmailHaveSite($formData['import_site_id']);
        if (!$flag) {
            $returnData['status'] = 1;
            $returnData['okNum'] = 0;
            $returnData['errorInfo'] = "没有相关网站的权限";
            echo json_encode($returnData);
            exit;
        }
        
        $formData['site_id'] = $formData['import_site_id'];
        $returnData = Yii::$app->usermanagemarket->uploadCsv('loadUnscribesList.csv');
         // 说明上传文件成功 可以开始导入相关数据了
        if ($returnData['status'] == 0) {
            $returnInfoData = Yii::$app->usermanagemarket->importUnscribesCsv( $returnData['fileName'],$formData);
            
            $returnData['errorInfo'] = 'success';
            $returnData['okNum'] = $returnInfoData['okNum'];
            $returnData['badNum'] = $returnInfoData['badNum'];
        } else {
            $returnData['okNum'] = 0;
            $returnData['badNum'] = 0;
        }
    
        $returnData['site_id'] = $formData['import_site_id'];
        echo json_encode($returnData);
        exit;
    }
    
    /**
     * 导入ebay第三方用户标签
     */
    public function actionImportEbayTag()
    {
        set_time_limit(0);
        // 初始化
        $importTagSiteIdArr = [31,25]; // 目前只有ebay支持标签导入功能
        // csv 数据导入
        $returnData = [];
        $siteInfo = [];
        $countData = ['totalCount'=>0,'successCount'=>0,'failCount'=>0,'filterCount'=>0];
        $userGroupModel = new UserGroup();
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
        $session    = Yii::$app->session;

        // 查询网站相关的数据
       // $formData = Yii::$app->request->$mothod();
       $formData = $_REQUEST;
         // 模拟数据
//        $formData['user_list'] = <<<EOF
//yumao@globalegrow.com,yu
//815227173@qq.com,mao
//EOF;
//        echo '<pre>';
//        var_dump($_REQUEST);
//        var_dump($formData);
//        exit;
        // 判断权限
        if (empty($formData['site_id'])) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "没有传递site_id";
            $returnData['data'] = $countData;
            echo json_encode($returnData);
            exit;
        } elseif(!in_array($formData['site_id'],$importTagSiteIdArr)) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "当前网站暂不支持导入分群";
            $returnData['data'] = $countData;
            echo json_encode($returnData);
            exit;
        }
        $formData['import_site_id'] = $formData['site_id'];
        $flag = Yii::$app->authority->judgeMarketEmailHaveSite($formData['import_site_id']);
        
        if (!$flag) {
            $returnData['status'] = 1;
           
            $returnData['errorInfo'] = "没有相关网站的权限";
            $returnData['data'] = $countData;
            echo json_encode($returnData);
            exit;
        } 
        if (empty($formData['user_group_id'])) {
            $returnData['status'] = 1;
           
            $returnData['errorInfo'] = "没有传递user_group_id";
            $returnData['data'] = $countData;
            echo json_encode($returnData);
            exit;
        }
       
        if (empty($formData['user_list'])) {
            $returnData = Yii::$app->usermanagemarket->uploadCsv('loadTagList.csv',$formData);
            if ($returnData['status'] == 0) { // 上传成功做其他的相关操作
                // 遍历数据加入到数据表中
                $returnInfoData = Yii::$app->usermanagemarket->importEbayTagUser($formData,$returnData['fileName'],'',$returnData['suffix']);
            } else {
                $returnData['data'] = $countData;
                echo json_encode($returnData);
                exit;
            }
        } else {
            $returnInfoData = Yii::$app->usermanagemarket->importEbayTagUser($formData,'',$formData['user_list']);
        }
        echo json_encode($returnInfoData);
    }
    /**
     * 根据用户标识批量导入用户
     */
   public function actionImportFlag()
    {
        set_time_limit(0);
        // csv 数据导入
        $returnData = [];
        $siteInfo = [];
        
        $userGroupModel = new UserGroup();
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
        $session    = Yii::$app->session;
        
        
        
        // 查询网站相关的数据
        $formData = Yii::$app->request->$mothod();
        
        // 判断权限
        $flag = Yii::$app->authority->judgeMarketEmailHaveSite($formData['import_site_id']);
        if (!$flag) {
            $returnData['status'] = 1;
            $returnData['okNum'] = 0;
            $returnData['errorInfo'] = "没有相关网站的权限";
            echo json_encode($returnData);
            exit;
        } 
        $formData['site_id'] = $formData['import_site_id'];
        
        // 数据处理
        $formData['import_user_identification_name'] = addslashes($formData['import_user_identification_name']);
        if (!empty($formData['user_flag_exclude'])) {
            $formData['user_flag_exclude'] = addslashes($formData['user_flag_exclude']);
        }
        $returnData = Yii::$app->usermanagemarket->uploadCsv('loadFlagList.csv');
        // $returnData['status'] = 0;
        // $returnData['fileName'] = ROOT_PATH.'/upload/gamiss/blackcsv/loadFlagList.csv';
        
       
        // 说明上传文件成功 可以开始导入相关数据了
        if ($returnData['status'] == 0) {
            $returnInfoData = Yii::$app->usermanagemarket->importCsvFlag( $returnData['fileName'],$formData);
            // 判断当前分群是否存在，有没有被删除
            if($this->isDuplicate($formData['import_site_id'],$formData['import_user_identification_name'])) {
                 $userGroupModel->updateByCondition(['user_group_name' => $formData['import_user_identification_name']],
                ["is_del" => 1, "reviser_real_name" => $session['admin_info']['real_name'], "del_time" => time()]);
            } 
            
            // 往user_group表中插入相关记录
            $userFlag = [];
            $userFlag['user_flag'] =  $formData['import_user_identification_name'];
            $data = [];
            $data['site_id'] = $formData['import_site_id'];
            $data['user_group_name'] = $formData['import_user_identification_name'];
            $data['user_group_type'] = 7; // 代表标签用户分群
            $data['description'] = $formData['import_user_identification_name'];
            $data['reviser_real_name'] = $session['admin_info']['real_name'];
            $data['is_sys'] = 1;
            $data['user_count'] = $returnInfoData['userGroupNum'];
            $data['form_data'] = "";
            $data['other_con'] = json_encode($userFlag);
            $data['update_time'] = time();
            $data['use_time'] = time();
             // 添加到数据库
            $siteName = Yii::$app->params['sites']['marketing_email']['web_index'][$formData['site_id']];
            $siteInfo = yii::$app->params['sites']['marketing_email']['web_config'][$siteName];
            if (!empty($siteInfo['accessEs'])) {
                // 添加es相关条件
                $filterInfoArr = [];
                $filterInfoArr['filters'] = [];
                $esFilterArrTemp = [];
                $esFilterArrTemp["field"] = 'userFlag';
                $esFilterArrTemp["values"] = [$formData['import_user_identification_name']];
                $filterInfoArr['filters'][] = $esFilterArrTemp;
                $data['es_filters'] = json_encode($filterInfoArr);
            } 
            $groupId = $userGroupModel->addUserGroup($data);
            $tableName = 'user_'.Yii::$app->params['sites']['marketing_email']['web_index'][$formData['site_id']];
           
            $listData = [];
            $listData['businessType'] = 12;
            $listData['operateType'] = 2;
            $listData['site'] = strtolower($siteName);
            $listData['create_time'] = time();
            $listData['error_times'] = 0;
            $listData['user_count_sql'] = "select count(*) from {$tableName} where user_flag = '{$formData['import_user_identification_name']}'";
            $listData['user_group_sql'] = "update user_group  set user_count = :user_count,is_import_over=1 where user_group_id=$groupId";
            Yii::$app->usermanagemarket->pushImportDataRedisList($siteName,$listData);
            $returnData['okNum'] = $returnInfoData['okNum'];
            $returnData['userGroupNum'] = 0;
        } else {
            $returnData['okNum'] = 0;
            $returnData['userGroupNum'] = 0;
        }
    
        //$returnData['status'] = 0;
        //$returnData['errorInfo'] = 'success';
        $returnData['site_id'] = $formData['import_site_id'];
        echo json_encode($returnData);
        exit;
        
    }
    
    /**
     * 是否有重复的分群
     * @param $siteId                   站点id
     * @param $userGroupName            分群名称
     * @param null $userGroupId         分群id
     * @return bool
     */
    private function isDuplicate($siteId, $userGroupName, $userGroupId = null,$userGroupType = 7)
    {
        $userGroupModel = new UserGroup();
        $group = $userGroupModel->getByCondition(["site_id" => $siteId, "user_group_name" => $userGroupName, "is_del" => 0,'user_group_type' => 7]);
        if (empty($group)) {
            return false;
        }
        if (!empty($userGroupId) && $userGroupId == $group[0]["user_group_id"]) {
            return false;
        }
        return true;
    }
    /**
     * 批量导入黑名单相关
     */
    public function actionImportBlack()
    {
        // 黑名单导入
        $returnData = [];
        $siteInfo = [];
        
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
        // 查询网站相关的数据
        $formData = Yii::$app->request->$mothod();
        $returnData = Yii::$app->usermanagemarket->uploadCsv();
        
        if ($returnData['status'] == 0) { // 说明上传文件成功 可以开始导入相关数据了
            $returnData['okNum'] = Yii::$app->usermanagemarket->importCsv( $returnData['fileName'],$formData);
        }
        echo json_encode($returnData);
        exit;
    }
    
    /**
     * 导出黑名单数据
     */
    public function actionOutBlack()
    {
        $mothod = strtolower(Yii::$app->request->getMethod());
        
        // 当前的系统，代表是营销邮件还是系统邮件
        $site = Yii::$app->request->$mothod('site');
        
        $formData = Yii::$app->request->$mothod();
        // 用户退订
        $returnData = Yii::$app->usermanagemarket->outBlack($formData);
        echo json_encode($returnData);
        exit;
    }
    
    /**
     * 导入测试
     */
    public function actionImportTest()
    {
        $fileName = ROOT_PATH.'/upload/trendsgal/blackcsv/loadBlackList.csv';
        Yii::$app->usermanagemarket->importCsv($fileName);
        exit;
    }
    
    /**
     * 黑名单列表
     */
     public function actionBlackList()
    {
        $data = [];
        $siteInfo = [];
        
        $defaultPageSize = 20;
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
         // 查询网站相关的数据
        $formData = Yii::$app->request->$mothod();
        // 当前用户所有有权限的站点
        $siteInfo_tmp = Yii::$app->authority->getMarketEmailAccessSite();
        
      
        //$siteInfo[0] = '网站';
        if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
            foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
                $siteInfo[$siteInfo_tmp_v['site_id']] = $siteInfo_tmp_v['name'];
            }
        }
        if (empty($siteInfo)) {
            exit('你好，你没有任何网站的相关权限');
        }
        
        // 当前用户所有有权限的站点结束
        $formData['siteInfo'] = $siteInfo;
       
          // 用户邮箱
        $formData['email'] = isset($formData['email']) ? $formData['email'] : '';
        if (!empty($formData['reservation_time'])) {
            $reservationTimeArr = explode(' - ',$formData['reservation_time']);
            $formData['startTime'] = $reservationTimeArr[0];
            $formData['endTime'] = $reservationTimeArr[1];
        }
        
         // 时间相关
        $formData['time_type'] = isset($formData['time_type']) ? $formData['time_type'] : 1;
        $timeYearMonth = \yii::$app->bjTime->date('Y-m',time());
        $timeYearMonthStart = $timeYearMonth.'-01';
        $timeYearMonthCurrent = \yii::$app->bjTime->date('Y-m-d',time());
        
        $formData['startTime'] = isset($formData['startTime']) ? $formData['startTime'] : $timeYearMonthStart;
        $formData['endTime'] = isset($formData['endTime']) ? $formData['endTime'] : $timeYearMonthCurrent;
        
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://'; 
        $formUrl = explode('?',$http_type.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"])[0]; 
        
        //$importUrl = explode('?',$http_type.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"])[0]; 
        // 当前搜索哪个网站的用户信息
        $formData['site_id'] = isset($formData['site_id']) ? $formData['site_id'] : array_keys($siteInfo)[0];
        
        // 搜索用户标签
        $formData['label'] = isset($formData['label']) ? $formData['label'] : 1;
        
        // 根据什么条件搜索邮箱
        $formData['email_search_condition'] = isset($formData['email_search_condition']) ? $formData['email_search_condition']:1;
        if ($formData['site_id']) {
            $flag = Yii::$app->authority->judgeMarketEmailHaveSite($formData['site_id']);
            if (!$flag) {
                 $this->sysMsg('警告', '你的账号没有权限!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
            }
        } 
        
        // 分页参数相关
        $page = Yii::$app->request->$mothod('page') ? Yii::$app->request->$mothod('page') : 1;
        $pageSize = Yii::$app->request->$mothod('pagesize') ? Yii::$app->request->$mothod('pagesize') : $defaultPageSize;
       
        $formData['page'] = $page;
        $formData['pageSize'] = $pageSize;
        
        
        // 保存用户结果数据
        $data_select = Yii::$app->usermanagemarket->getMarketBlockUserList($formData);
        $totalCount = $data_select['totalCount'];
         // 分页相关
        $pages = new Pagination(['totalCount' =>$totalCount, 'pageSize' => $pageSize, 'defaultPageSize' => $pageSize]);
        return $this->render('//marketing//user-manage/black-list',[
            'data' => $data_select['user_info'],  
            'formData' => $formData,
            'site' => $site,
            'formUrl' => $formUrl,
            //'importUrl' => $importUrl,
            'pages' => $pages,
        ]);
    }

    /**
     * 添加队列
     * @return string
     */
    public function actionAddSendQueue()
    {
        yii::$app->db->enableSlaves = false;        // 禁用从库查询，从主库查询数据。防止生成子分组时主从不同步
        $data = $this->getAddSendQueueData();
        
        if (is_string($data)) {
            echo $data;
            exit();
        }
        $data['user_count'] = count($data['user']);
        $data['user'] = $this->formatUser($data['user']);
        $userManageMarket = new UserManageMarket();
        $data = $userManageMarket->getSendInfo($data);
        return $this->render('/marketing/user-manage/add-send-queue', [
            'data' => $data
        ]);
    }
    
    /**
     * 添加队列
     * @return string
     */
    public function actionAddTestNoSendQueue()
    {
        $data = $this->getAddTestNoSendQueueData();
        
        if (is_string($data)) {
            echo $data;
            exit();
        }
        
        $data['channel'] = [2 => 'emarsys', 4 => 'cheet', 6 => 'emarsys_new',5 => 'benchmark', 9 => 'webpower'];
        $data['user_count'] = intval($data['userNums']);
        
       
        return $this->render('/marketing/user-manage/add-test-no-send-queue', [
            'data' => $data
        ]);
    }
    /**
     * 获取 添加发送队列 的数据
     * @return string
     */
    private function getAddSendQueueData()
    {
        $method = yii::$app->request->getMethod();
        $data = yii::$app->request->$method();

        if (!isset($data['user_id'], $data['site_id'])) {
            return "数据不完整";
        }

        $site = new \app\components\Site();
        $siteName = $site->getSiteShortNameById($data['site_id']);
        if (empty($siteName)) {
            return "站点不存在";
        }
        $data['brief_code'] = $site->getBriefCode($data['site_id']);
        if (empty($data['brief_code'])) {
            return "站点没有简码";
        }

        $data['site_name'] = $siteName;
        if (1 == $data['checkType']) {      // 一键全选
            $userIdArr = $this->searchUserId($data);
            if (empty($userIdArr)) {
                return "用户不存在";
            }
        } else {        // 普通选择具体用户
            $userIdArr = explode(',', $data['user_id']);
        }

        $userModel = new User();
        $data['user'] = $userModel->getUserById($data['site_name'], $userIdArr);

        $template = new \app\models\marketing\MailTemplate();
        if(isset($data['type']) && $data['type'] == 'ab_test') {
            $data['template'] = $template->getAbTestTemplateDetailById($data['site_id'],$data['template_id']);
        } else {
            $data['template'] = $template->getTemplateDetailBySite($data['site_id']);
        }
        
        
        
        $curBjTime = \yii::$app->bjTime->time();
        $curBjDate = \yii::$app->bjTime->date('ymd',$curBjTime);
        foreach ($data["template"] as $key => $value) {
            $data['template'][$key]['group_name_prefix'] = $value['template_type_compaign'];
            if (empty($value['template_type_compaign'])) {     // 如果compaign为空，则使用模板名来作为分组名的前缀
                $data['template'][$key]['group_name_prefix'] = $value['template_name'];
            }
            $data['template'][$key]['track_code'] = str_replace("{sendTime}", $curBjTime, $value['track_code']);
            $data['template'][$key]['track_code'] = str_replace("{sendDate}", $curBjDate, $data['template'][$key]['track_code']);
            
             // 如果包含custom_track_code 则要剔除掉
            if (!empty($data['template'][$key]['custom_track_code'])) {
                $data['template'][$key]['track_code'] = rtrim($data['template'][$key]['track_code'],'&'.$data['template'][$key]['custom_track_code']);
            } 
        }

        $data['mail'] = \app\components\Site::getInstance()->getMailSender($data['site_id']);

        return $data;
    }
    
    /**
     * 获取 添加发送队列 的数据
     * @return string
     */
    private function getAddTestNoSendQueueData()
    {
        $method = yii::$app->request->getMethod();
        $data = yii::$app->request->$method();

        if (!isset($data['group_id'], $data['site_id'])) {
            return "数据不完整";
        }

        $site = new \app\components\Site();
        $siteName = $site->getSiteShortNameById($data['site_id']);
        if (empty($siteName)) {
            return "站点不存在";
        }
        $data['brief_code'] = $site->getBriefCode($data['site_id']);
        if (empty($data['brief_code'])) {
            return "站点没有简码";
        }
        

        $groupModel = new MailGroup();
        $data['template'] = $groupModel->getAllTemplateInfoByTestParentGroup($data['group_id']);
        
        $data['site_name'] = $siteName;
        
        
        
        $curBjTime = \yii::$app->bjTime->time();
        $curBjDate = \yii::$app->bjTime->date('ymd',$curBjTime);
        foreach ($data["template"] as $key => $value) {
            $data['template'][$key]['group_name_prefix'] = $value['template_type_compaign'];
            if (empty($value['template_type_compaign'])) {     // 如果compaign为空，则使用模板名来作为分组名的前缀
                $data['template'][$key]['group_name_prefix'] = $value['template_name'];
            }
            $data['template'][$key]['track_code'] = str_replace("{sendTime}", $curBjTime, $value['track_code']);
            $data['template'][$key]['track_code'] = str_replace("{sendDate}", $curBjDate, $data['template'][$key]['track_code']);
            
             // 如果包含custom_track_code 则要剔除掉
            if (!empty($data['template'][$key]['custom_track_code'])) {
                $data['template'][$key]['track_code'] = rtrim($data['template'][$key]['track_code'],'&'.$data['template'][$key]['custom_track_code']);
            } 
        }

        $data['mail'] = \app\components\Site::getInstance()->getMailSender($data['site_id']);

        return $data;
    }

    /**
     * 根据条件搜索用户id数据
     * @param $condition
     * @return array
     */
    private function searchUserId($condition)
    {
        // 搜索用户标签
        $condition['label'] = isset($condition['label']) ? $condition['label'] : 1;

        // 根据什么条件搜索邮箱
        $condition['email_search_condition'] = isset($condition['email_search_condition']) ? $condition['email_search_condition']:1;
        if ($condition['site_id']) {
            $flag = Yii::$app->authority->judgeMarketEmailHaveSite($condition['site_id']);
            if (!$flag) {
                $this->sysMsg('警告', '你的账号没有权限!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
            }
        }

        // 用户邮箱
        $condition['email'] = isset($condition['email']) ? $condition['email'] : '';
        if (!empty($condition['reservation_time'])) {
            $condition['reservation_time'] = str_replace("+", " ", $condition['reservation_time']);
            $reservationTimeArr = explode(' - ',$condition['reservation_time']);
            $condition['startTime'] = $reservationTimeArr[0];
            $condition['endTime'] = $reservationTimeArr[1];
        }
        $userIdArr = [];
        $idArr = Yii::$app->usermanagemarket->getMarketUserListIdArr($condition);
        foreach ($idArr as $id) {
            $userIdArr[] = $id['user_id'];
        }
        return $userIdArr;
    }

    /**
     * 格式化用户数据
     * @param $user
     * @return mixed
     */
    private function formatUser($user)
    {
        $subState = [0 => "未订阅", 1 => "订阅", 2 => "退订"];
        foreach ($user as $key => $value) {
            $user[$key]['email'] = Yii::$app->email->emailDispProcess(Yii::$app->emailmarket->decryption($value['email']));
            $user[$key]['reg_time'] = \yii::$app->bjTime->date("Y-m-d H:i", $value['reg_time']);
            $label = [];
            if (array_key_exists($value['is_received_promo'], $subState)) {
                $label[] = $subState[$value['is_received_promo']];
            }
            if ($value['is_test']) {
                $label[] = "内测";
            }
            if ($value['is_complaint']) {
                $label[] = "投诉";
            }
            $user[$key]['label'] = $label;
        }
        return $user;
    }

    public function actionGetTemplate()
    {
        $method = yii::$app->request->getMethod();
        $siteId = yii::$app->request->$method('site_id');
        $data = yii::$app->request->$method();

        if (empty($siteId)) {
            $this->returnJson(10001, "数据不完整");
        }

        $template = new \app\models\marketing\MailTemplate();
        $data = $template->getTemplate(["site_id" => $siteId, "is_del" => 0]);
        $this->returnJson(0, "success", $data);
    }



}

